package com.treeroot.treenet.protocol.abs.tcp.decode;

import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

/**
 * Description: 帧解码
 * Create By TreeRoot
 * Create Time: 2025/06/02 10:13
 * Class Name: FrameDecoder
 *
 * @author TreeRoot
 */
@Slf4j
public class FrameDecoder {

    /**
     * 8KB
     */
    private static final int MAX_PAYLOAD_LENGTH = 8 * 1024;
    /**
     * 累积量
     */
    private final ByteBuffer cumulation;
    /**
     * 解码器
     */
    private final MessageDecoder decoder;

    public FrameDecoder(MessageDecoder decoder) {
        this.decoder = decoder;
        this.cumulation = ByteBuffer.allocate(1024 * 16);
    }

    /**
     * 解码消息
     *
     * @param readBuffer 读缓冲区
     * @return {@link List }<{@link DecodedMessage }>
     */
    public List<DecodedMessage> decode(ByteBuffer readBuffer) {
        List<DecodedMessage> messages = new ArrayList<>();
        cumulation.put(readBuffer);
        cumulation.flip();

        while (true) {
            cumulation.mark();
            DecodedMessage message = decoder.decode(cumulation);
            if (message == null) {
                cumulation.reset();
                break;
            }
            if (message.getPayload().length() > MAX_PAYLOAD_LENGTH) {
                log.warn("payload 超出最大长度限制，丢弃该消息");
                continue;
            }
            messages.add(message);
        }
        cumulation.compact();
        return messages;
    }
}